package com.strato.mvc.menu.v1_0_0.impl;

import java.util.Map;

import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.mvc.api.v1_0_0.view.ModelEnhancer;
import com.strato.mvc.menu.v1_0_0.Menu;
import com.strato.mvc.menu.v1_0_0.MenuStore;

@OsgiService
public class MenuStoreImpl implements MenuStore,ModelEnhancer {

	private Menu root;
	
	public MenuStoreImpl(){
		root=new Menu();
	}
	
	@Override
	public void store(String group,String path, Menu menu) {
		if(path.startsWith("/")){
			path=path.substring(1);
		}
		String pathWithGroup=group+"/"+path;
		String[] names=pathWithGroup.split("/");
		Menu node=root;
		for(int i=0,len=names.length;i<len;i++){
			String name=names[i];
			Menu sub=node.getSubMenu(name);
			if(sub==null){
				sub=new Menu();
				node.addSubMenu(name,sub);
				if(sub.getText()==null){
					sub.setText(name);
				}
				sub.setNodeName(name);
			}
			if(i==len-1){
				merge(sub,menu);
			}else{
				node=sub;
			}
		}
	}

	private void merge(Menu dst, Menu add) {
		dst.setIncludeContext(add.isIncludeContext());
		dst.setPath(add.getPath());
		dst.setText(add.getText());
		dst.setIcon(add.getIcon());
		dst.setUrl(add.getUrl());
		dst.setOrder(add.getOrder());
	}

	@Override
	public Menu load(String group,String path) {
		if(path.startsWith("/")){
			path=path.substring(0);
		}
		String pathWithGroup=group+"/"+path;
		String[] names=pathWithGroup.split("/");
		Menu node=root;
		Menu sub=null;
		for(int i=0,len=names.length;i<len;i++){
			String name=names[i];
			sub=node.getSubMenu(name);
			if(sub==null){
				break;
			}
			node=sub;
		}
		return sub;
	}

	@Override
	public void enhance(Map<Object, Object> model) {
		model.put("menuStore", this);
	}

}
